using System.Activities;
using System.Activities.Statements;
using System.Collections.Generic;
using System.Linq;
using Headsight.BPMN2WF.Transformation;

namespace Headsight.BPMN2WF.WF.Simplification
{
    /// <summary>
    /// <see cref="IWFSimplifier"/> implementation simplifying <see cref="Sequence"/>s by
    /// integrating child <see cref="Sequence"/>s' <see cref="Activity"/> into the parent
    /// <see cref="Sequence"/>.
    /// </summary>
    public class WFSimplifierSequence : IWFSimplifier
    {
        public BPMNTransformationResult Simplify(IBPMN2WFTransformationContext ctx, BPMNTransformationResult transformationResult)
        {
            var result = transformationResult;
            var sequence = (Sequence)result.Result;

            if (sequence.Activities.Count == 0)
            {
                return result;
            }

            sequence = Simplify(sequence);
            
            return new BPMNTransformationResult(sequence, 
                sequence.Activities.FirstOrDefault(), 
                (result.FlowOut != null) ? sequence.Activities.LastOrDefault() : null);
        }

        public bool Probe(IBPMN2WFTransformationContext ctx, BPMNTransformationResult transformationResult)
        {
            return (transformationResult.Result is Sequence);
        }

        private static Sequence Simplify(Sequence sequence)
        {
            var activites = new List<Activity>(sequence.Activities);
            sequence.Activities.Clear();

            foreach (var each in activites)
            {
                if (each is Sequence)
                {
                    foreach (var each2 in ((Sequence)each).Activities)
                    {
                        sequence.Activities.Add(each2);
                    }
                }
                else
                {
                    sequence.Activities.Add(each);
                }
            }

            return sequence;
        }
    }
}